package com.heima.search.service.impl;

import com.heima.common.dtos.ResponseResult;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    @Async
    public void insert(Integer userId, String keyword) {
        //判断当前用户是否搜索过该关键词
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch userSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        if(userSearch!=null){
            //搜索过，更新最新时间即可
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);//本质上是更新
            return;
        }

        //没有搜索过，判断当前用户的搜索条数是否大于10
        Query userQuery = Query.query(Criteria.where("userId").is(userId));
        //按时间倒序
        userQuery.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> userSearchList = mongoTemplate.find(userQuery, ApUserSearch.class);

        ApUserSearch newSearch = new ApUserSearch();
        newSearch.setUserId(userId);
        newSearch.setKeyword(keyword);
        newSearch.setCreatedTime(new Date());

        if(userSearchList==null || userSearchList.size()<10){
            //如果小于10，则直接添加到DB即可
            mongoTemplate.save(newSearch);
        }else{
            //如果大于或等于10，替换最后1条记录
            //获取最后1条
            ApUserSearch lastSearch = userSearchList.get(userSearchList.size() - 1);

            //直接使用新对象来替换数据库中旧数据
            /**
             * 参数一：需要被替换的数据的查询条件
             * 参数二：替换成新的对象
             */
            Query deleteQuery = Query.query(Criteria.where("_id").is(lastSearch.getId()));
            mongoTemplate.findAndReplace( deleteQuery , newSearch);
        }
    }

    @Override
    public ResponseResult<List<ApUserSearch>> load() {
        ApUser apUser =(ApUser)ThreadLocalUtils.get();
        if(apUser==null){
            return ResponseResult.okResult(null);
        }

        Query userQuery = Query.query(Criteria.where("userId").is(apUser.getId()));
        //按时间倒序
        userQuery.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> userSearchList = mongoTemplate.find(userQuery, ApUserSearch.class);

        return ResponseResult.okResult(userSearchList);
    }

    @Override
    public ResponseResult del(HistorySearchDto dto) {
        return ResponseResult.okResult(mongoTemplate
                .remove(Query.query(Criteria.where("_id").is(dto.getId())),
                        ApUserSearch.class));
    }
}
